package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyComment;
import cn.wolfcode.trip.base.domain.Tag;
import cn.wolfcode.trip.base.mapper.StrategyCommentMapper;
import cn.wolfcode.trip.base.mapper.TagMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyCommentService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private StrategyCommentMapper strategyCommentMapper;

    @Autowired
    private TagMapper tagMapper;

    @Override
    public void saveOrUpdate(StrategyComment strategyComment,String[] tags) {
        if(strategyComment.getId()!=null){
            strategyCommentMapper.updateByPrimaryKey(strategyComment);
        }else{
            //设置用户
            strategyComment.setUser(UserContext.getCurrentUser());
            //保存评论
            strategyCommentMapper.insert(strategyComment);

            for (String name : tags) {
                Tag tag = new Tag();
                tag.setName(name);
                //保存标签
                tagMapper.insert(tag);
                //中间表关联
                strategyCommentMapper.insertRelation(tag.getId(),strategyComment.getId());
            }

        }
    }

    @Override
    public StrategyComment getById(Long id) {
        return strategyCommentMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<StrategyComment> listByUserId(Long id) {
        return strategyCommentMapper.listByUserId(id);
    }

    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<StrategyComment> list = strategyCommentMapper.selectForList(qo);
        return new PageInfo(list);
    }

}
